<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="wap-font-scale" content="no">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="X-UA-Compatible" content="IE=7" />
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >
    <title><?php echo isset($title) ? $title : env('APP_TITLE'); ?></title>
    <link rel="stylesheet" href="/statics_v2/css/app.css">
    <script src="/statics_v2/js/libs/jquery.min.js"></script>
    <script src="/statics_v2/js/libs/fastclick.js"></script>
    <script src="/statics_v2/js/app.js"></script>

    <link rel="stylesheet" href="/layim/dist/css/layui.mobile.css" />
    <script type="text/javascript" src="/layim/dist/layui.js"></script>
    <style>
        .navRightBtn{
            display: none;
        }
        .layim-title {
            background: #333333
        }

        .layim-chat-footer {
            display: flex;
            position: fixed;
            bottom: 0;
            right: 10px;
            width: 100%;
            left: 0 !important;
            padding: 10px !important;
            box-sizing: border-box !important;
            background: #fff !important;
            height: 60px !important;
        }

        .layim-chat-tool {
            width: 58px;
        }

        .layim-chat-send {
            width: 100% !important;
        }

        .layim-chat-send button {
            white-space: nowrap;
            background-color: #63d4f0 !important;
            position: static;
            right:0;
            z-index: 9;
            width: 11px;
            padding: 0 !important;
            width: 60px;
            display: none;
        }

        .layim-chat-tool {
            width: 40% !important;
            justify-content: space-evenly;
            display: flex;

        }

        .layim-chat-send input {
            border: 1px #ddd solid !important;
            color: #000;
        }

        .layim-chat-mine .layim-chat-text {
            background-color: #36373c !important;
        }

        .layim-chat-mine .layim-chat-text:after {
            border-top-color: #36373c !important;
        }
        .layui-m-layermain, .layui-m-layershade,.layim-panel,.layim-chat-main, .layim-content,.layim-chat-footer{
            position: absolute;
        }
        .layim-chat-tool span {
            position: relative;
            margin: 0 15px;
            display: inline-block;
            vertical-align: top;
            font-size: 28px;
            cursor: pointer;
            width: 30px;
            margin: 0 !important;
            padding: 0 0px;
            color:#666;
        }

        .layim-content,.layim-chat-send{
            user-select: text !important;
            -webkit-user-select: text !important;
            -ms-user-select:text !important;
            -moz-user-select:text !important;
        }
        input {
            -webkit-user-select:auto !important;
            user-select: auto !important;
            -ms-user-select:auto !important;
            -moz-user-select:auto !important;
        }

    </style>
</head>
<body<?php if (isset($controller)) echo ' data-controller="' . $controller . '"'; ?> ontouchstart>

<script src="/statics_v2/js/libs/highstock/highstock.js"></script>
<script src="/statics_v2/js/libs/technical-indicators.js"></script>
<script>
    var imgUploadUrl="http://gzmxkj.com/upload"; //图片上传
    //本人
    var from_id ="<?php echo $user['id_wechat']; ?>";
    var name = "<?php echo $user['id_wechat']; ?>";
    var avatar ="/statics_v2/img/defaultAvatar.png";
    var phone = "<?php echo $user['id_wechat']; ?>";
    //对象
    var kid = "k001";
    var k_name = '客服';
    var k_avatar = 'http://gzmxkj.com/layui/images/kf.jpg';

    //var host = "http://192.168.1.43/five_elements/laravel56/public/";
    var host='http://gzmxkj.com';


    layui.config({
        version: true
    }).use('mobile', function() {
        var mobile = layui.mobile,
            layim = mobile.layim,
            layer = mobile.layer;
        var socket = new WebSocket('ws://gzmxkj.com:9501');


        //演示自动回复
        /*  var autoReplay = [
          '你没发错吧？face[微笑] ',
            '洗澡中，请勿打扰，偷窥请购票，个体四十，团体八折，订票电话：一般人我不告诉他！face[哈哈] ',
            '你好，我是主人的美女秘书，有什么事就跟我说吧，等他回来我会转告他的。face[心] face[心] face[心] ',
            'face[威武] face[威武] face[威武] face[威武] ',
            '<（@￣︶￣@）>',
            '你要和我说话？你真的要和我说话？你确定自己想说吗？你一定非说不可吗？那你说吧，这是自动回复。',
            'face[黑线]  你慢慢说，别急……',
            '(*^__^*) face[嘻嘻] ，是贤心吗？'
        ];*/


        layim.config({
            //上传图片接口
             uploadImage: {
               url: imgUploadUrl//（返回的数据格式见下文）
               ,type: 'post' //默认post
             },

            //上传文件接口
            /*,uploadFile: {
              url: '/upload/file' //（返回的数据格式见下文）
              ,type: '' //默认post
            }*/
            brief: true,
            init: {
                //我的信息
                mine: {
                    "username": name, //我的昵称
                    "id": from_id, //我的ID
                    avatar: avatar
                },
                //我的好友列表
                friend: []
            }

            //扩展聊天面板工具栏
            /*,tool: [{
              alias: 'code'
              ,title: '代码'
              ,iconUnicode: '&#xe64e;'
            }]*/

            //扩展更多列表
            /*,moreList: [{
              alias: 'find'
              ,title: '发现'
              ,iconUnicode: '&#xe628;' //图标字体的unicode，可不填
              ,iconClass: '' //图标字体的class类名
            },{
              alias: 'share'
              ,title: '分享与邀请'
              ,iconUnicode: '&#xe641;' //图标字体的unicode，可不填
              ,iconClass: '' //图标字体的class类名
            }]*/

            //,tabIndex: 1 //用户设定初始打开的Tab项下标
            //,isNewFriend: false //是否开启“新的朋友”
            //,isgroup: true //是否开启“群聊”
            //,chatTitleColor: '#c00' //顶部Bar颜色
            //,title: 'LayIM' //应用名，默认：我的IM
        });

        /* var wsUri ="ws://echo.websocket.org/";
           var webSocket = new WebSocket(wsUri);*/
        //alert(socket.readyState)

        //socket.send('Hi Server, I am LayIM!');

        //连接成功时触发
        socket.onopen = function() {
            console.log('ok')

        };
        //监听收到的消息
        socket.onmessage = function(res) {
            var obj = JSON.parse(res.data);
            var obj2 = {
                content: obj.data,
                username: obj.username,
                id: kid, //聊天窗id
                type: obj.type,
                avatar: obj.avatar
            }
            if(obj.type == 'init') {
                var params = {
                    "from_id": from_id,
                };
                var ajaxUrl = host+'/chat/load';
                $.post(ajaxUrl, params, function(res) {
                    $.each(res.data, function(i, e) {
                        //对象
                        var obj2={
                            avatar:e.from_avatar,
                            content:e.content,
                            username:e.from_name,
                            id:e.from_id, //聊天窗id
                            type: 'friend'
                        }
                        obj2.mine = false;
                        layim.getMessage(obj2);

                    })
                })

                var msg = {
                    from_id: from_id,
                    type: 'bind'
                }
                console.log(obj);
                socket.send(JSON.stringify(msg));
            } else if(obj.type == 'say') {

                obj2.type = 'friend';
                obj2.mine = false;
                console.log(obj);
                layim.getMessage(obj2);

            } else if(obj.type == 'save') {
                //入库
                var params = {
                    "from_id": obj.from_id,
                    "to_id": obj.to_id,
                    "is_read": obj.isRead,
                    "content": obj.data,
                    'from_name':phone,
                    'from_avatar':avatar,
                };
                $.ajax({
                    type: "post",
                    dataType: "json",
                    async:false,
                    url: host+'/chat/save',
                    data:params,
                    success: function (res) {

                    },
                });

            }
            //     else if(obj.type == 'save'){
            //     //入库
            //     var url = 'http://192.168.40.128/save.php';
            //     var data = {"from_id":obj.from_id,"to_id":obj.to_id,"isRead":obj.isRead,"content":obj.data};
            //     $.post(url,data,function (data,status) {
            //     })
            // }
            else {

            }

            //res为接受到的值，如 {"emit": "messageName", "data": {}}
            //emit即为发出的事件名，用于区分不同的消息
        };

        socket.onerror = function() {
            console.log("onerror")
        };

        socket.onclose = function(res) {
            console.log("onclose")
        };

        layim.chat({
            name: k_name //名称
            ,
            type: 'friend' //聊天类型
            ,
            avatar:k_avatar,
            id: kid //好友id
        });

        //创建一个会话
        /*
        layim.chat({
          id: 111111
          ,name: '许闲心'
          ,type: 'kefu' //friend、group等字符，如果是group，则创建的是群聊
          ,avatar: 'http://tp1.sinaimg.cn/1571889140/180/40030060651/1'
        });
        */

        //监听点击“新的朋友”
        /*  layim.on('newFriend', function(){
            layim.panel({
              title: '新的朋友' //标题
              ,tpl: '<div style="padding: 10px;">自定义模版，{{d.data.test}}</div>' //模版
              ,data: { //数据
                test: '么么哒'
              }
            });
          });*/

        //查看聊天信息
        /*  layim.on('detail', function(data){
            //console.log(data); //获取当前会话对象
            layim.panel({
              title: data.name + ' 聊天信息' //标题
              ,tpl: '<div style="padding: 10px;">自定义模版，<a href="http://www.layui.com/doc/modules/layim_mobile.html#ondetail" target="_blank">参考文档</a></div>' //模版
              ,data: { //数据
                test: '么么哒'
              }
            });
          });*/

        //监听点击更多列表
        /* layim.on('moreList', function(obj){
           switch(obj.alias){
             case 'find':
               layer.msg('自定义发现动作');

               //模拟标记“发现新动态”为已读
               layim.showNew('More', false);
               layim.showNew('find', false);
             break;
             case 'share':
               layim.panel({
                 title: '邀请好友' //标题
                 ,tpl: '<div style="padding: 10px;">自定义模版，{{d.data.test}}</div>' //模版
                 ,data: { //数据
                   test: '么么哒'
                 }
               });
             break;
           }
         });*/

        //监听返回
        //layim.on('back', function() {
        //history.back();
        /*layer.open({
            type:2
        });*/
        //layer.load();
        /*setTimeout(function() {
            location.href = "{php echo mobileUrl('pc.cms_doctor.mobile')}" + "&page=jumpFaq";
        }, 1000)*/

        //history.back();
        //window.location.href="{php echo mobileUrl('pc.cms_doctor.mobile')}";
        //如果你只是弹出一个会话界面（不显示主面板），那么可通过监听返回，跳转到上一页面，如：history.back();
        //});

        //监听自定义工具栏点击，以添加代码为例
        /*layim.on('tool(code)', function(insert, send){
          insert('[pre class=layui-code]123[/pre]'); //将内容插入到编辑器
          send();
        });*/

        $(".layim-chat-back").removeAttr("layim-event");
        //返回
        $(".layim-chat-back").bind("click",function(){
            //parent.chatBack();
            history.back();
        });

        //监听发送消息
        layim.on('sendMessage', function(data) {
            $(".layim-chat-send button").hide();

            var To = data.to;
            var mine = data.mine;
            var msg = {
                type: 'say',
                avatar:avatar,
                from_id: from_id,
                to_id: kid,
                username: phone,
                name: '健康咨询',
                text: mine.content
            }
            socket.send(JSON.stringify(msg));
            //console.log(data);

            // 第一次发送客服自动回复
             if(!$(".layim-chat-send button").hasClass('notFirst')){
                 $(".layim-chat-send button").addClass('notFirst');
                //演示自动回复
                setTimeout(function(){
                    var obj = {};
                    if(To.type === 'group'){
                        obj = {
                            username: '模拟群员'+(Math.random()*100|0)
                            ,avatar: layui.cache.dir + 'images/face/'+ (Math.random()*72|0) + '.gif'
                            ,id: To.id
                            ,type: 'group'
                            // ,content: autoReplay[Math.random()*9|0]
                            ,content: '你好！易金汇客服为你服务'
                        }
                    } else {
                        obj = {
                            username: To.name
                            ,avatar: To.avatar
                            ,id: To.id
                            ,type: To.type
                            // ,content: autoReplay[Math.random()*9|0]
                            ,content: '你好！易金汇客服为你服务'
                        }
                    }
                    layim.getMessage(obj);
                }, 2000);
             }


        });

        $(function() {
            /*var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
            $(window).on("resize",function(){
                var nowClientHeight = document.documentElement.clientHeight || document.body.clientHeight;
                if (clientHeight > nowClientHeight) {
                    var focus=$(".layim-chat-send input:focus");
                    var offset =focus.offset();
                    if(nowClientHeight/2<offset.top){
                        var top=nowClientHeight/2-offset.top;
                    }
                    $(".layim-panel").css('top',top);
                    //键盘弹出的事件处理     x  -x
                    //$("footer").hide();
                }
                else {
                    //键盘收起的事件处理
                   // $("footer").show();
                    $(".layim-panel").css('top',0);
                }

            });
*/
            //解决手机软键盘遮住input方法
         /*   $(".layim-chat-send input").on("click", function() {
                var target = this;
                setTimeOut(function() {
                    target.scrollIntoView(true);
                }, 300);
            });*/
            //输入框聚焦
           /* $(".layim-chat-send input").focus(function(){
                var target = this;
                setTimeout(function() {
                    // 设置body的高度为可视高度+302
                    // 302为原生键盘的高度
                    //$(".layim-chat-send input").onfocus();
                    //$(".layim-chat-footer").css({"top":50,"bottom":"auto"});
                    document.getElementsByTagName('body')[0].style.height = (window.innerHeight + 402) + 'px';
                    document.body.scrollTop = 402;
                    //target.scrollIntoView(true);
                }, 300)
            });*/

            //输入框失焦
           /* $(".layim-chat-send input").blur(function(){
                var target = this;
                document.getElementsByTagName('body')[0].style.height = window.innerHeight + 'px';
                //target.scrollIntoView(true);
            });*/


            //实时监听输入框
            $('.layim-chat-send input').bind('input propertychange', function() {
                var con=$(this).val();
                if($.trim(con)!=""){
                    $(".layim-chat-send button").show();
                }else{
                    $(".layim-chat-send button").hide();
                }
            });



        })
        //模拟收到一条好友消息
        /*setTimeout(function(){
          layim.getMessage(
              {
            username: "俊男"
            ,avatar: "http://tp1.sinaimg.cn/1571889140/180/40030060651/1"
            ,id: "100001"
            ,type: "friend"
            ,cid: Math.random()*100000|0 //模拟消息id，会赋值在li的data-cid上，以便完成一些消息的操作（如撤回），可不填
            ,content: "你好"
          });
        }, 3000);*/

        //监听查看更多记录
        /* layim.on('chatlog', function(data, ul){
           console.log(data);
           layim.panel({
             title: '与 '+ data.name +' 的聊天记录' //标题
             ,tpl: '<div style="padding: 10px;">这里是模版，{{d.data.test}}</div>' //模版
             ,data: { //数据
               test: 'Hello'
             }
           });
         });*/


    });
</script>
</body>
</html>
